package com.ruoyi.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.water.domain.Element;
import com.ruoyi.water.domain.MeterAnalyse;
import com.ruoyi.water.domain.MeterWarn;
import com.ruoyi.water.domain.WarnType;
import com.ruoyi.water.mapper.MeterWarnMapper;
import com.ruoyi.water.service.IElementService;
import com.ruoyi.water.service.IMeterAnalyseService;
import com.ruoyi.water.service.IMeterWarnService;
import com.ruoyi.water.service.IWarnTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

@Service
public class MeterWarnServiceImpl extends ServiceImpl<MeterWarnMapper, MeterWarn> implements IMeterWarnService {

    @Autowired
    private IMeterAnalyseService meterAnalyseService;

    @Autowired
    private IElementService elementService;

    @Autowired
    private IWarnTypeService warnTypeService;

    @Override
    public void generateMeterWarnings(Date startDate, Date endDate) {
        // 1. 查询指定日期范围内的所有分析数据
        QueryWrapper<MeterAnalyse> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("analyseDate", startDate, endDate);
        List<MeterAnalyse> analyseList = meterAnalyseService.list(queryWrapper);

        // 2. 遍历每条分析数据，进行告警判断
        for (MeterAnalyse analyse : analyseList) {
            // 获取对应的水表信息
            Element element = elementService.getById(analyse.getMeterId());
            if (element == null) {
                continue; // 水表不存在则跳过
            }

            // 3. 进行各类告警判断
            checkAndCreateWarning(analyse, element, 1, analyse.getTodayMinvalPercent());
            checkAndCreateWarning(analyse, element, 2, analyse.getMonthagoMinvalPercent());
            checkAndCreateWarning(analyse, element, 3, analyse.getYearagoMinvalPercent());
            checkAndCreateWarning(analyse, element, 4, analyse.getTodayUsagePercent());
            checkAndCreateWarning(analyse, element, 5, analyse.getMonthagoUsagePercent());
            checkAndCreateWarning(analyse, element, 6, analyse.getYearagoUsagePercent());
        }
    }

    /**
     * 检查并创建告警
     */
    private void checkAndCreateWarning(MeterAnalyse analyse, Element element, int warnType, Double value) {
        // 值为空则跳过
        if (value == null) {
            return;
        }

        // 获取告警级别
        Integer warnLevel = getWarnLevel(value, element.getFirstWarn(), element.getSecondWarn(), element.getThirdWarn());
        if (warnLevel == null) {
            return; // 不满足告警条件
        }

        // 获取告警类型名称
        WarnType warnTypeInfo = warnTypeService.getOne(new QueryWrapper<WarnType>()
                .eq("warnType", warnType)
                .eq("object", "meter"));
        if (warnTypeInfo == null) {
            return;
        }

        // 创建告警信息
        MeterWarn warn = new MeterWarn();
        warn.setMeterId(analyse.getMeterId());
        warn.setElemName(analyse.getMeterName());
        warn.setWarnLevel(warnLevel);
        warn.setWarnType(warnType);
        warn.setWarnMsg(buildWarnMessage(analyse, warnTypeInfo.getWarnName(), value, warnLevel));
        warn.setWarnTime(analyse.getAnalyseDate());
        warn.setWarnStatus(false); // 默认未处理状态
        warn.setRecordTime(new Date());

        // 保存告警记录
        this.save(warn);
    }

    /**
     * 确定告警级别
     */
    private Integer getWarnLevel(Double value, Double firstWarn, Double secondWarn, Double thirdWarn) {
        if (thirdWarn != null && value >= thirdWarn) {
            return 3;
        } else if (secondWarn != null && value >= secondWarn) {
            return 2;
        } else if (firstWarn != null && value >= firstWarn) {
            return 1;
        }
        return null;
    }

    /**
     * 构建告警信息
     */
    private String buildWarnMessage(MeterAnalyse analyse, String warnName, Double percent, int level) {
        StringBuilder msg = new StringBuilder();
        msg.append(analyse.getMeterName()).append(warnName).append("-");

        switch (warnName) {
            case "最小瞬时流量大于最小流量基准":
                msg.append(String.format("水表当日最小流量百分比为%.2f%%, 达到%d级告警阈值", percent, level));
                break;
            case "最小瞬时流量环比大于阈值":
                msg.append(String.format("水表当日最小流量环比百分比为%.2f%%, 达到%d级告警阈值", percent, level));
                break;
            case "最小瞬时流量同比大于阈值":
                msg.append(String.format("水表当日最小流量同比百分比为%.2f%%, 达到%d级告警阈值", percent, level));
                break;
            case "当日用水大于每日用水基准":
                msg.append(String.format("水表当日用水百分比为%.2f%%, 达到%d级告警阈值", percent, level));
                break;
            case "当日用水环比大于阈值":
                msg.append(String.format("水表当日用水环比百分比为%.2f%%, 达到%d级告警阈值", percent, level));
                break;
            case "当日用水同比大于阈值":
                msg.append(String.format("水表当日用水同比百分比为%.2f%%, 达到%d级告警阈值", percent, level));
                break;
        }
        return msg.toString();
    }
}